package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import common.CommException;
import domain.User;
/**
 * 处理注册用户的请求
 * @author cqyhm
 *
 */
import Service.UserService;
@WebServlet(urlPatterns= {"/register.do"})
public class RegisterServlet extends HttpServlet {

	private static final long serialVersionUID = 122930306584885273L;
	
	private Logger logger=LoggerFactory.getLogger(getClass());
	
	private UserService userService=new UserService();
	/**
	 * 处理get方法发送过来的请求
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	/**
	 * 处理post方法发送过来的请求
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.debug("dopost");
		logger.info("register.dopost");
		try {
			//1.接收前台传递过来的参数
			String usercode=req.getParameter("usercode");
			String username=req.getParameter("username");
			String password=req.getParameter("password");
			
			String confirm=req.getParameter("confirm");
			String email=req.getParameter("email");
			
			//2.参数类型转换
			//3.参数合法性校验
			//账号不能为空
			if(usercode==null||usercode.length()<=0) {
			   throw new CommException("账号不能为空");
			}
			
			//新密码不能为空
			if(password==null||password.length()<=0) {
				throw new CommException("密码不能为空");
			}
			//重新输入的密码不能为空
			if(confirm==null||confirm.length()<=0) {
				throw new CommException("重新输入密码不能为空");
			}
			logger.debug("asdsd");
			//两次输入的密码不相等
			if(!confirm.equals(password)) {
				throw new CommException("两次输入的密码不相等。");
			}
			//4.参数封装为对象
			User user=new User();
			user.setUsercode(usercode);
			user.setUsername(username);
			user.setPassword(password);
			user.setEmail(email);
			//5.调用业务方法
			userService.register(user);
			//6.1.转发或重定向(可传递数据给页面)
			resp.sendRedirect(req.getContextPath()+"/login.jsp");//重定向
			logger.info("注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			//6.2.转发或重定向(可传递错误信息给页面)
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/register.jsp").forward(req, resp); //转发
			logger.error("注册失败：{}",e.getMessage());
		}
	}

}
